const UserModel = require('../models/user')
const bcrypt = require('bcryptjs')
const formidable = require("formidable")
const fs = require('fs')
const xlsx = require('node-xlsx');

// 设计用户的表模型
const mongoose = require('mongoose')
const Schema = mongoose.Schema
// 好友表结构
const friendsListSchema = new Schema({
    remarksName: {
        type: String,
        require: true
    },
    username: {
        type: String,
        require: true
    },
    account: {
        type: String,
        require: true
    },
    timeToBeFriend: {
        type: String,
        require: true
    },
})
// 申请好友表结构
const applyFriendListSchema = new Schema({
    processStatus: {
        type: String,
        require: true
    },
    username: {
        type: String,
        require: true
    },
    account: {
        type: String,
        require: true
    },
    sendTime:{
        type: String,
        require: true
    },
})
// 聊天记录表结构
const chatRecordSchema = new Schema({
    chatRecord: {
        type: String,
        require: true
    },
    chatRecordType: {
        type: String,
        require: true
    },
    sendUser: {
        type: String,
        require: true
    },
    sendTime:{
        type: String,
        require: true
    },
})
// 聊天列表结构
const chatListSchema = new Schema({
    lastChatRecord: {
        type: String,
        require: true
    },
    friendRemarksName: {
        type: String,
        require: true
    },
    friendAccount: {
        type: String,
        require: true
    },
    sendTime:{
        type: String,
        require: true
    },
})
// 下载文件表结构
const downloadFiles = new Schema({
    fileId: {
        type: String,
        require: true
    },
    fileName: {
        type: String,
        require: true
    },
    fileRoute: {
        type: String,
        require: true
    },
    sendUser: {
        type: String,
        require: true
    },
})

module.exports = {
    // 登录
    async login(ctx, next) {
        // console.log(ctx.request.body);
        let { account, password } = ctx.request.body
        const user = await UserModel.findOne({ account })
        if((await UserModel.find({ account })).length && await bcrypt.compare(password, user.password)){
            ctx.body = {
                msg: '登录成功',
                body: user,
            }
        }else ctx.body = { msg: '用户名/密码错误' }

    },
    // 注册
    async register(ctx, next) {
        // console.log(ctx.request.body);
        let { username, account, password } = ctx.request.body
        if((await UserModel.find({ account })).length) ctx.body = { msg: '账号重复' }
        else{
            let newuser = {
                username, account, 
                password: await bcrypt.hash(password, bcrypt.genSaltSync(10)), // 加密十次
                friendList: account + 'FriendList',
                registerDate: new Date(),
                lastLoginDate: new Date(),
            }
            await UserModel.create(newuser)
            // 好友列表
            mongoose.model(account + 'FriendList', friendsListSchema)
            await mongoose.model(account + 'FriendList', friendsListSchema).create({ 
                username, account,
                remarksName: username,
                timeToBeFriend: new Date(),
            })
            // 申请好友列表
            mongoose.model(account + 'ApplyFriendList', applyFriendListSchema)
            // 添加自己为好友
            await mongoose.model(account + account + 'chatRecord', chatRecordSchema).create({
                chatRecord: '欢迎使用仿·微信聊天工具', 
                chatRecordType: 'text',
                sendUser: account,
                sendTime: new Date(),
            })
            // 聊天列表
            mongoose.model(account + 'chatList', chatListSchema)
            await mongoose.model(account + 'chatList', chatListSchema).create({
                lastChatRecord: '欢迎使用仿·微信聊天工具',
                friendRemarksName: username,
                friendAccount: account,
                sendTime: new Date(),
            })
            // 下载文件列表
            mongoose.model(account + 'downloadFilesList', downloadFiles)
            
            ctx.body = { msg: '注册成功' }
        }

    },
    // 搜索用户
    async searchUser(ctx, next) {
        // console.log(ctx.request.body);
        let { searchData, userData } = ctx.request.body
        let findUser = await UserModel.find({ account: searchData })
        let friendsListData = await mongoose.model(userData.account + 'FriendList', friendsListSchema).find({account: new RegExp(searchData)})
        let isFriend = friendsListData.length == [] ? false : true
        let remarksName = isFriend ? friendsListData[0].remarksName : findUser[0].username
        if(findUser.length){
            let userData = {
                isFriend, remarksName,
                username: findUser[0].username,
                account: findUser[0].account,
            }
            ctx.body = { 
                msg: '查询成功',
                body: userData,
            }
        }else ctx.body = { msg: '无用户信息' }
    },
    // 搜索好友
    async searchFriend(ctx, next){
        // console.log(ctx.request.body);
        let { searchData, userData } = ctx.request.body
        let friendList = await mongoose.model(userData.account + 'FriendList', friendsListSchema).find({account: new RegExp(searchData)})
        ctx.body = { msg: '成功', friendList, }
    },
    // 发送添加好友请求
    async sendFriendRequest(ctx, next){
        // console.log(ctx.request.body);
        let { userData, searchUserData } = ctx.request.body
        let friendRequest = await mongoose.model(searchUserData.account + 'ApplyFriendList', applyFriendListSchema).find({
            username: userData.username,
            account: userData.account,
        })
        if(friendRequest.length == 0){
            await mongoose.model(searchUserData.account + 'ApplyFriendList', applyFriendListSchema).create({
                processStatus: 'unhandled',
                remarksName: userData.username, 
                username: userData.username,
                account: userData.account,
                sendTime: new Date(),
            })
            ctx.body = { msg: '好友申请发送成功' }
        }else{
            await mongoose.model(searchUserData.account + 'ApplyFriendList', applyFriendListSchema).updateOne({ 
                username: userData.username,
                account: userData.account,
            }, { sendTime: new Date() })
            ctx.body = { msg: '请勿重复发送' }
        }
    },
    // 查看好友请求列表
    async getFriendRequestList(ctx, next){
        // console.log(ctx.request.body);
        let { userData } = ctx.request.body
        ctx.body = { 
            msg: '成功',
            friendRequestList: await mongoose.model(userData.account + 'ApplyFriendList', applyFriendListSchema).find(),
        }
    },
    // 处理好友申请
    async precessFriendRequest(ctx, next){
        // console.log(ctx.request.body);
        let { applyResult, applyUserData, userData } = ctx.request.body
        if (applyResult == 'accept') {
            await mongoose.model(userData.account + 'FriendList', friendsListSchema).create({
                remarksName: applyUserData.username,
                username: applyUserData.username, 
                account: applyUserData.account,
                timeToBeFriend: new Date(),
            })
            await mongoose.model(applyUserData.account + 'FriendList', friendsListSchema).create({
                remarksName: userData.username,
                username: userData.username, 
                account: userData.account,
                timeToBeFriend: new Date(),
            })
            let shcemName = [applyUserData.account, userData.account].sort()
            await mongoose.model(shcemName[0] + shcemName[1] + 'chatRecord', chatRecordSchema).create({
                chatRecord: '我们已经成为好友了', 
                chatRecordType: 'text',
                sendUser: userData.account,
                sendTime: new Date(),
            })
            await mongoose.model(userData.account + 'chatList', chatListSchema).create({
                lastChatRecord: '我们已经成为好友了',
                friendRemarksName: applyUserData.username,
                friendAccount: applyUserData.account,
                sendTime: new Date(),
            })
            await mongoose.model(applyUserData.account + 'chatList', chatListSchema).create({
                lastChatRecord: '我们已经成为好友了',
                friendRemarksName: userData.username,
                friendAccount: userData.account,
                sendTime: new Date(),
            })
            
        }
        await mongoose.model(userData.account + 'ApplyFriendList', applyFriendListSchema).updateOne({ 
            username: applyUserData.username,
            account: applyUserData.account,
        }, {
            processStatus: applyResult
        })
        ctx.body = { msg: '成功', }
    },
    // 修改备注
    async editRemarksName(ctx, next){
        console.log(ctx.request.body);
        let { remarksName, friendUserData, userData } = ctx.request.body
        await mongoose.model(userData.account + 'FriendList', friendsListSchema).updateOne({
            account: friendUserData.account,
        }, { remarksName })
        ctx.body = {
            msg: '成功',
            friendUserData: await mongoose.model(userData.account + 'FriendList', friendsListSchema).findOne({ account: friendUserData.account })
        }
    },
    // 获取聊天记录
    async getChatRecord(ctx, next){
        // console.log(ctx.request.body);
        let { userData, chackUserData } = ctx.request.body
        let shcemName = [chackUserData.account, userData.account].sort()
        ctx.body = { 
            msg: '成功',
            chatRecord: await mongoose.model(shcemName[0] + shcemName[1] + 'chatRecord', chatRecordSchema).find(),

        }
    },
    // 发送信息
    async sendMessage(ctx, next){
        // console.log(ctx.request.body);
        let { userData, chackUserData, sendMessage } = ctx.request.body
        let chatRecordType = 'text'
        if (sendMessage.indexOf('uploadFiles') != -1) { chatRecordType = 'files' }
        let shcemName = [chackUserData.account, userData.account].sort()
        await mongoose.model(shcemName[0] + shcemName[1] + 'chatRecord', chatRecordSchema).create({
            chatRecord: sendMessage, 
            chatRecordType,
            sendUser: userData.account,
            sendTime: new Date(),
        })
        await mongoose.model(userData.account + 'chatList', chatListSchema).updateOne({
            friendAccount: chackUserData.account,
        },{
            lastChatRecord: sendMessage,
            sendTime: new Date(),
        })
        await mongoose.model(chackUserData.account + 'chatList', chatListSchema).updateOne({
            friendAccount: userData.account,
        },{
            lastChatRecord: sendMessage,
            sendTime: new Date(),
        })
        ctx.body = { msg: '成功', }
    },
    async getChatList(ctx, next){
        // console.log(ctx.request.body);
        let { userData } = ctx.request.body
        let chatList = await mongoose.model(userData.account + 'chatList', chatListSchema).find()
        chatList.sort((a, b) => new Date(b.sendTime).getTime() - new Date(a.sendTime).getTime())
        ctx.body = { msg: '成功', chatList}
    },  
    // 上传文件
    async uploadFiles(ctx, next){
        // console.log(ctx.request.files.file);
        let { path, name } = ctx.request.files.file
        ctx.body = { msg: '成功', path, name };
    },
    async editFilesDetail(ctx, next){
        // console.log(ctx.request.body)
        let { path, name, userData, chackUserData } = ctx.request.body
        let newPath = path + '-' + userData.account + chackUserData.account + '-' + name
        fs.rename(path, newPath, (err)=>{ })
        let fileId = path.substring(path.lastIndexOf('\\') + 1, path.length)
        console.log(fileId);
        mongoose.model(userData.account + 'downloadFilesList', downloadFiles).create({
            fileId,
            fileName: name,
            fileRoute: newPath.substring(path.lastIndexOf('\\'), newPath.length),
            sendUser: chackUserData.account,
        })
        mongoose.model(chackUserData.account + 'downloadFilesList', downloadFiles).create({
            fileName: name,
            fileRoute: newPath.substring(path.lastIndexOf('\\'), newPath.length),
            sendUser: userData.account,
        })
        ctx.body = { msg: '成功', sendMessage: 'uploadFiles' + '-' +  fileId + '-' + name}
    },

    // 下载文件
    async downloadFiles(ctx, next){
        console.log(ctx.request.body)
        let { fileId, userData } = ctx.request.body
        ctx.body = { msg: '成功', filesData: await mongoose.model(userData.account + 'downloadFilesList', downloadFiles).findOne({ fileId }) }
    },
}